﻿using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Hsp.Net4.Common.LogUtil
{
    public class Log4netWriter
    {
        // A项目调用时，在A下添加CSharpUtils项目引用，并放一份log4net.config
        //Log4netWriter.WriteLog(new LogEventArgs(typeof(Program), LogLevel.ERROR, "日志唉唉唉", ex));

        private static readonly Object m_lock = new object();
        private static LogEventHandler formLogEventHandler = null;
        private Log4netWriter()
        {
        }

        public static void RegistFormLogEventHandler(LogEventHandler handler)
        {
            formLogEventHandler += handler;
        }

        public static void UnRegistFormLogEventHandler(LogEventHandler handler)
        {
            formLogEventHandler -= handler;
        }

        public static void WriteLog(LogEventArgs e)
        {
            InnerWriteLog(e);
            if (formLogEventHandler != null)
            {
                formLogEventHandler.Invoke(e);
            }
        }
        private static void InnerWriteLog(LogEventArgs e)
        {
            if (e == null)
                return;
            ILog logger = e.Type == null ? LogManager.GetLogger("") :
                LogManager.GetLogger(e.Type);
            switch (e.Level)
            {
                case LogLevel.DEBUG:
                default:
                    {
                        logger.Debug(e.Msg, e.Ex);
                        break;
                    }
                case LogLevel.ERROR:
                    {
                        logger.Error(e.Msg, e.Ex);
                        break;
                    }
                case LogLevel.INFO:
                    {
                        logger.Info(e.Msg, e.Ex);
                        break;
                    }
                case LogLevel.WARN:
                    {
                        logger.Warn(e.Msg, e.Ex);
                        break;
                    }
                case LogLevel.FATAL:
                    {
                        logger.Fatal(e.Msg, e.Ex);
                        break;
                    }
            }
        }
    }

}
